//
//  FSCLoginController.swift
//  FamiliesSchoolConnection
//
//  Created by 花花蔡 on 2016/12/22.
//  Copyright © 2016年 com.HuaHuaCai. All rights reserved.
//

import UIKit
import SVProgressHUD

class FSCLoginController: UIViewController {

    var loginBtn:UIButton!
    let loginBtnSpace:CGFloat = 30
    var setBtn:UIButton!
    let setBtnSpace = screenHeight * 0.037
    
    let logoY = screenHeight * 0.182
    let labelCenter = CGPoint(x: screenWidth/2, y: screenHeight * 0.36)
    var accountTextField:UITextField!
    var passwordTextField:UITextField!
    
    let whiteWidth = screenWidth * 0.722
    let whiteHeight = screenHeight * 0.131
    
    let centerX = screenWidth/2
    
    let loginMessage = UserDefaults.standard.value(forKey: LoginKey) as? NSDictionary
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        get {
            return .lightContent
        }
    }
    
//MARK:视图生命周期
    //退出键盘
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        setupUI()
        
    }
    
    func setupUI() -> Void {

        //背景图
        let iamgeView = UIImageView(frame: UIScreen.main.bounds)
        let bkImage = UIImage(named: "login_bg")
        iamgeView.image = bkImage
        view.addSubview(iamgeView)
        

        guard let iamge = UIImage(named: "logo") else {
            return
        }
        
        //图片层
        let imageLayer = CALayer()
        imageLayer.bounds = CGRect(x: 0.0, y: 0.0, width: 100, height: 100)
        imageLayer.position = CGPoint(x: centerX, y: logoY)
        imageLayer.contents = iamge.cgImage
        iamgeView.layer.addSublayer(imageLayer)
        
        //倒影层
        let reflectionLayer = CALayer()
        reflectionLayer.bounds = CGRect(x: 0, y: 0.5, width: 100, height: 100)
        reflectionLayer.position = CGPoint(x: centerX, y: logoY + 90)
        reflectionLayer.contents = imageLayer.contents
        reflectionLayer.setValue(180, forKeyPath: "transform.rotation.x")
        
        //遮罩层
        let graduentLayer = CAGradientLayer()
        graduentLayer.bounds = reflectionLayer.bounds
        graduentLayer.position = CGPoint(x: reflectionLayer.bounds.size.width/2, y: reflectionLayer.bounds.size.height)
        graduentLayer.colors = [UIColor.clear.cgColor,UIColor.black.cgColor]
        //y：改变遮罩的程度，即透明度
        graduentLayer.startPoint = CGPoint(x: 0.3, y: 0)
        graduentLayer.endPoint = CGPoint(x: 0.3, y: 2.0)
        reflectionLayer.mask = graduentLayer
        iamgeView.layer.addSublayer(reflectionLayer)
        
        //app名字label
        let nameLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 250, height: 30))
        nameLabel.center = labelCenter
        nameLabel.text = "枣 尚 家 校 通"
        nameLabel.textAlignment = .center
        nameLabel.textColor = UIColor.white
        nameLabel.font = UIFont.boldSystemFont(ofSize: 28)
        iamgeView.addSubview(nameLabel)
       
        //app名字英文版
        let englishLY = nameLabel.frame.maxY + 10
        let englishL = UILabel(frame: CGRect(x: 0, y: englishLY, width: 140, height: 16))
        englishL.center.x = screenWidth/2
        englishL.text = "Zao Smart Class"
        englishL.textAlignment = .center
        englishL.textColor = UIColor.lightGray
        englishL.font = UIFont.systemFont(ofSize: 14)
        iamgeView.addSubview(englishL)
        
        //登录框
        let whiteViewY = englishL.frame.maxY + 15
        
        let whiteV = UIView(frame: CGRect(x: 0, y: whiteViewY, width: whiteWidth, height: whiteHeight))
        whiteV.center.x = centerX
        whiteV.backgroundColor = UIColor.white
        whiteV.layer.cornerRadius = 5
        whiteV.layer.masksToBounds = true
        iamgeView.addSubview(whiteV)
        
        let lineWhite = UIView(frame: CGRect(x: 0, y: whiteV.frame.height/2, width: whiteV.bounds.width, height: 1))
        lineWhite.backgroundColor = UIColor.lightGray
        whiteV.addSubview(lineWhite)

        accountTextField = UITextField(frame: CGRect(x: whiteV.frame.origin.x, y: whiteV.frame.origin.y, width: whiteV.bounds.width, height: whiteV.frame.height/2))
        accountTextField.placeholder = "请输入账号"
        accountTextField.clearButtonMode = .whileEditing
        accountTextField.leftView = setTextFieldLeftV(imageName: "icon_user")
        accountTextField.returnKeyType = .next
        accountTextField.leftViewMode = .always
        accountTextField.keyboardType = .numbersAndPunctuation
        accountTextField.tag = btnBaseTAG + 1
        accountTextField.delegate = self
        view.addSubview(accountTextField)
        
        passwordTextField = UITextField(frame: CGRect(x: whiteV.frame.origin.x, y: accountTextField.frame.maxY, width: whiteV.bounds.width, height: whiteV.bounds.height/2))
        passwordTextField.placeholder = "请输入密码"
        passwordTextField.clearButtonMode = .whileEditing
        passwordTextField.leftViewMode = .always
        passwordTextField.keyboardType = .numbersAndPunctuation
        //passwordTextField.isSecureTextEntry = true
        passwordTextField.leftView = setTextFieldLeftV(imageName: "icon_password")
        passwordTextField.returnKeyType = .done
        passwordTextField.delegate = self
        view.addSubview(passwordTextField)
        
        
        //初始化登录按钮
        let btnY = whiteV.frame.maxY + loginBtnSpace
        loginBtn = UIButton(type: .custom)
        loginBtn.frame = CGRect(x: 0, y: btnY, width: 200, height: 44)
        loginBtn.center.x = centerX
        loginBtn.setTitle("登录", for: .normal)
        loginBtn.tag = btnBaseTAG + 1
        loginBtn.addTarget(self, action: #selector(loginBtnClicked), for: .touchUpInside)
        guard let btnImage = UIImage(named:"feedbackBtn_n") else {
            return
        }
        loginBtn.setBackgroundImage(btnImage, for: .normal)
        loginBtn.layer.borderWidth = 1.0
        loginBtn.layer.borderColor = UIColor.cyan.cgColor
        loginBtn.layer.cornerRadius = 4
        loginBtn.layer.masksToBounds = true
        view.addSubview(loginBtn)
        
        //设置按钮
        let setBtnY = loginBtn.frame.maxY + setBtnSpace
        setBtn = UIButton(type: .custom)
        setBtn.frame = CGRect(x: 0, y: setBtnY, width: 40, height: 40)
        setBtn.center.x = centerX
        setBtn.tag = btnBaseTAG + 2
        setBtn.addTarget(self, action: #selector(loginBtnClicked), for: .touchUpInside)
        let setImageN = UIImage(named: "settings_nor")
        let setImageH = UIImage(named: "settings_press")
        setBtn.setImage(setImageN, for: .normal)
        setBtn.setImage(setImageH, for: .highlighted)
        view.addSubview(setBtn)
        
        
        guard let loginMessage = loginMessage else {
            return
        }
        accountTextField.text = loginMessage["code"] as? String
        passwordTextField.text = loginMessage["password"] as? String


    }
    
//textField的leftView
    func setTextFieldLeftV(imageName:String) -> UIView {
        //创建一个背景视图
        let bgView = UIView(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
        //获得图片
        let img = UIImage(named: imageName)
        //创建第一张图片视图
        let firstV = UIImageView(image: img)
        firstV.center = CGPoint(x: (img?.size.width)!/2 + 8, y: 22)
        bgView.addSubview(firstV)
        //创建第二张图片
        let secondV = UIImageView(image: UIImage(named: "line_edit_sep"))
        secondV.center = CGPoint(x: firstV.frame.maxX +
            10, y: 22)
        bgView.addSubview(secondV)
        
        return bgView
    }
    
    //登录按钮的监听回调方法
    func loginBtnClicked(btn:UIButton) -> Void {
        switch btn.tag - btnBaseTAG {
        case 1:
            SVProgressHUD.show(withStatus: "登录中....")
            //判断学校IP是否设置
            guard baseURLStr == nil || baseURLStr == "http://120.24.57.38/new/" else {
                SVProgressHUD.showInfo(withStatus: "学校IP地址错误")
                return
            }
            guard accountTextField.text != "" else {
                SVProgressHUD.showInfo(withStatus: "账号不能为空")
                return
            }
            guard passwordTextField.text != "" else {
                SVProgressHUD.showInfo(withStatus: "密码不能为空")
                return
            }

        //获得网络接口
        let urlStr =  "ZH-schoolname-S-login"
        //设置参数
        let parm = ["code":accountTextField.text!,"password":passwordTextField.text!]
    
        //调用网络单例方法请求数据
        FSCNetworkTools.shared.request(url: urlStr, parameters: parm, finish: { (data, error) in
            //判断并处理数据是否为空
            guard let data = data as? NSDictionary else {
                SVProgressHUD.showInfo(withStatus: "登录失败,请检查网络")
                return
            }

            //判断账号密码错误
            let result = data["result"] as! Int
            switch result {
                case 0:
                    print("设置登录")
                    //保存账号密码
                    UserDefaults.standard.set(parm, forKey:LoginKey)
                    //获得用户信息字典
                    let userInfo = data["data"] as! NSDictionary
                    //保存字典
                    UserDefaults.standard.set(userInfo, forKey: userInfoKey)
                    //保存登录状态
                    UserDefaults.standard.set(true, forKey: isLoginKey)
                    //获得主窗口
                    UIApplication.shared.keyWindow?.rootViewController = FSCDrawerController()
                case 1:
                    SVProgressHUD.showInfo(withStatus: "账号或者密码错误")
            default:
                    break
            }
            
        })
            
        
        default:
            
            let alertVC = UIAlertController(title: "请输入学校的IP地址", message: nil, preferredStyle: .alert)
            alertVC.addTextField(configurationHandler: { (textF) in
                textF.placeholder = "学校IP地址"
                //获得已经保存的地址
                textF.text = UserDefaults.standard.object(forKey: IPSaveKey) as! String?
//                textF.borderStyle = .roundedRect
            })
            
            alertVC.addAction(UIAlertAction(title: "取消", style: .destructive, handler: nil))
            
            alertVC.addAction( UIAlertAction(title: "确定", style: .default, handler: { (_) in
                
                //确定
                let inputIP = alertVC.textFields?[0].text ?? ""
                //记录保存当前输入内容
                UserDefaults.standard.set(inputIP, forKey: IPSaveKey)
            }))
        
            present(alertVC, animated: true, completion: nil)
        }
    }
    
    
    
}

extension FSCLoginController:UITextFieldDelegate {
    
//    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
//        
//        switch textField.tag - btnBaseTAG {
//        case 1:
//            passwordTextField.becomeFirstResponder()
//        default:
//            break
//        }
//        return true
//    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        
        switch textField.tag - btnBaseTAG {
        case 1:
            //账号
            if string == "\n" {
                passwordTextField.becomeFirstResponder()
            }
        default:
            if string == "\n" {
                textField.resignFirstResponder()
                loginBtnClicked(btn: loginBtn)
            }
        }
        
        return true
    }
}



